package Fiter;

import Damain.user;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CheckLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //数据转型
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //放行静态资源
        String requestURI = request.getRequestURI();
        if(requestURI.contains("/css/")||requestURI.contains("/images/")||requestURI.contains("/js/")){
            chain.doFilter(request, response);
            return;
        }

        //获取到请求地址
        String servletPath = request.getServletPath();
        System.out.println(servletPath);
        if (servletPath.contains("/userLoginServlet") || servletPath.contains("/login.jsp")) {
            chain.doFilter(request, response);
            return;
        }
        //获取到session
        user user = (user) request.getSession().getAttribute("user");
        //判断session
        if (user == null) {
            request.setAttribute("errorMsg", "请登录");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
